import { findUserByToken } from '@/api/user'
import { getToken, removeToken } from '@/utils/auth'

const user = {
  // namespaced: true,
  state: {
    token: getToken(),
    name: '',
    roles: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      // console.log(token)
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },
  actions: {
    // 获取用户信息
    GetUserInfo ({ commit }) {
      // console.log(this.getters.token)
      return new Promise((resolve, reject) => {
        findUserByToken(this.getters.token).then(res => {
          if (!res.data) {
            reject('验证失败 请重新登录')
          }
          const data = res.data
          // console.log('data:', data)
          if (data.roles && data.roles.length > 0) {
            // 验证返回的roles是否是一个非空数组
            var userRole = []
            for (const role of data.roles) {
              userRole.push(role)
            }
            commit('SET_ROLES', userRole)
          } else {
            reject('请等待管理员分配权限！')
          }
          resolve(res)
        })
      }).catch(error => {
        // reject(error)
        console.log('error:', error)
      })
    },

    // 前端登出
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
